<?php
/*
 * Created on 10.11.2009
 *
 * Protect email adress from spiders via javascript
 */

m2import('phpinchains/psp/Tag.php');

class xt_protectEmailHandler extends phpinchains_psp_Tag {

/**
 * Empty tag
 * @var int
 */
    public $tagType = PSP_EMPTY_TAG;
    /**
     * Tag name
     * @var string
     */
    public $tagName   = 'xt:protectEmail';

    public $requiredAttributes = array(
    'value' => '.*'
    );
    public $attributes = array(
    'value'
    );

    private $randomChars = 'abcdefghijklmnopqrstuvwxyz';

    function randomString($length)
    {
        $chars_length = (strlen($this->randomChars) - 1);
        $string = $this->randomChars{rand(0, $chars_length)};
        for ($i = 1; $i < $length; $i = strlen($string))
        {
            $r = $this->randomChars{rand(0, $chars_length)};
            if ($r != $string{$i - 1}) $string .=  $r;
        }
        return $string;
    }

    private function splitIt ($value) {
        $parts = array();
        while (strlen($value)) {
            $rand = rand(1, 5);
            if ($rand >= strlen($value)) {
                $parts[] = $value;
                break;
            } else {
                $parts[] = substr($value, 0, $rand);
                $value = substr($value, $rand);
            }
        }
        return $parts;
    }

    private function createVarDefs ($parts) {
        $jscode = "";
        $vars   = array();
        foreach ($parts as $part) {
            $var = $this->randomString(10);
            $jscode .= 'var '.$var.' = "'.str_replace('"','\"',$part)."\";\n";
            $vars[] = $var;
        }
        return array('jscode' => $jscode, 'vars' => $vars);
    }

    function doStartTag() {
        $htmlcode = '<a href="mailto:'.$this->getAttribute('value').'">'.$this->getAttribute('value').'</a>';
        $defs  = $this->createVarDefs($this->splitIt($htmlcode));
        $this->out->write('<script type="text/javascript">'."\n".$defs['jscode']."document.write(".join('+', $defs['vars']).");\n</script>");
        return PSP_SKIP_BODY;
    }

}
?>